#pragma once

#include "zqdb.h"
#include "zqstr.hpp"
#include "zqdb.pb.h"
#include "mdbdf.hpp"

namespace zqdb {

	template<class TStream>
	void SerializeTableTitleToCSV(TStream& os, HZQDB module, const char* table, const MDB_FIELD* attr, size_t attr_num)
	{
		for (size_t i = 0; i < attr_num; i++)
		{
			const char* name = ZQDBGetTableFiledName(module, table, i);
			if (i == 0) {
				if (name) {
					os << name;
				}
			}
			else {
				os << ",";
				if (name) {
					os << name;
				}
			}
		}
		os << "\n";
	}

	template<class TStream>
	void SerializeTableDataToCSV(TStream& os, const MDB_FIELD* attr, size_t attr_num, const char* data)
	{
		for (size_t i = 0; i < attr_num; i++)
		{
			if (i != 0) {
				os << ",";
			}
			char buf[1024] = { 0 };
			size_t buflen = 1024;
			char* sbuf = buf;
			char** val = &sbuf;
			size_t* sz = &buflen;
			mdb::FieldOp::GetValueAsStr(data, attr + i, 1, val, sz, nullptr);
			os << buf;
		}
		os << "\n";
	}

	template<class TStream>
	void SerializeDiffDataToCSV(TStream& os, size_t attr_num, const MDB_FIELD* diff, size_t diff_num, const char* data)
	{
		for (size_t i = 0, j = 0; i < attr_num; i++)
		{
			if (i != 0) {
				os << ",";
			}
			for (; j < diff_num; )
			{
				if (diff[j].index > i) {
					break;
				} else if (diff[j].index == i) {
					char buf[1024] = { 0 };
					size_t buflen = 1024;
					char* sbuf = buf;
					char** val = &sbuf;
					size_t* sz = &buflen;
					mdb::FieldOp::GetValueAsStr(data, diff + j, 1, val, sz, nullptr);
					os << buf;
					j++;
					break;
				}
				else {
					j++;
				}
			}
		}
		os << "\n";
	}

}
